import axios from 'axios';


// 使用promise
export default function request(opstions) {
    return new Promise((reslove, reject) => {
        const instance = axios.create({
            timeout: 5000,
            baseURL: "/api",//地址
            headers: { 'X-Requested-With': 'XMLHttpRequest' }
        })
        instance.interceptors.request.use(config => {
            // 配置toekn
            let token = localStorage.getItem("token");
            if (token) {
                // 将token设置到请求头
                config.headers.Authorization = token;

            }
            return config;
        }, err => {
            return err;
        })
        // 响应拦截
        instance.interceptors.response.use(res => {
            return res.data;
        }, err => {
            // 统一失败处理
            if (err && err.response) {
                switch (err.response.status) {
                    case 400:
                        err.message = "请求错误";
                        break;
                    case 500:
                        err.message = "服务器错误"
                        break;
                }
            }
            return err;
        })
        // 发送请求	
        instance(opstions).then(res => {
            reslove(res);
        }).catch(err => {
            reject(err);
        })
    })
}